/*===============================================
*   文件名称：main.c
*   创 建 者: 麦穗飘飘
*   创建日期：2024年12月14日   10:25:23
*   描    述：
================================================*/
#include "port.h"
#include "ultrasonic.h"
#include "sg90.h"

//extern struct message data;
extern struct get_information datas;
//extern char arr[4][1024];
extern float Hcsr04GetLength;

int flag = 1;

void *recvdata_function(){
	printf("recvdata\n");
	
	//get_datas();
	get_bufs();
}

void *recvimage_function(){
	#if 1
	int fd;
	int cfd;
	cfd = sever_to_client(8884, &fd);
	char buf[1024];
	memset(buf, 0, sizeof(buf));
	#if 1
	while(1){
		int read_buf=recv(cfd,buf,sizeof(buf),0);
		if(read_buf<0)//错误
		{
		    perror("recv");
		    printf("here\n");
		    close(cfd);
		}
		if(strcmp(buf, "get_data\n") == 0){
			printf("buf = %s\n", buf);
			send_signal();
			//break;
		}
		else{
			printf("error\n");
		}
	}
	#endif
		//send_signal();
	sleep(5);
	close(fd);
	close(cfd);
	#endif
	
}

int main(){
	pthread_t recvdata,recvimage; //capture;
	int ret;
	ret = pthread_create(&recvimage, NULL, recvimage_function, NULL);
	if (ret != 0) {
		// 创建线程失败
		perror("smoke_create error:");
		return 1;
    	}
   
    	ret = pthread_create(&recvdata, NULL,recvdata_function, NULL);
	if (ret != 0) {
		// 创建线程失败
		perror("humidity_create error:");
		return 1;
    	}
	
	int fd;
	int cfd;
	int fd1;
	int cfd1;
	cfd1 = sever_to_client(8886, &fd1);
	
	cfd = sever_to_client(8888, &fd);
	
	
	//send_image(cfd1);
	
	char buf[1024];
	memset(buf, 0, sizeof(buf));
	#if 1
	while(1){
		int read_buf=recv(cfd,buf,sizeof(buf),0);
		if(read_buf<0)//错误
		{
		    perror("recv");
		    printf("here\n");
		    close(cfd);
		}
		if(strcmp(buf, "get_data") == 0){
			printf("buf = %s\n", buf);
			break;
		}
		else{
			printf("error\n");
		}
	}
	#endif
	int flag = 0;
	int photo_flag = 1;
	while(1){
		printf("start\n");
		//send(cfd, "hello", 5, 0);
		if(flag == 0){
			//printf("%s\n", datas.temperature);
			send(cfd, datas.temperature, 1024, 0);
		}
		else if(flag == 1){
			//printf("%s\n", datas.humidity);
			send(cfd, datas.humidity, 1024, 0);
		}
		else if(flag == 2){
			//printf("%s\n", datas.MQ_2);
			send(cfd, datas.MQ_2, 1024, 0);
		}
		flag++;
		if(flag == 3){
			flag = 0;
		}
		
		if(Hcsr04GetLength < 6 && photo_flag){
			printf("1send_image\n");
			photo_flag = 0;
			send_image(cfd1);
			printf("2send_image\n");
		}
		
		if(Hcsr04GetLength > 10){
			photo_flag = 1;
		}
		/*printf("%s\n", datas.temperature);
		printf("%s\n", datas.humidity);
		printf("%f\n", Hcsr04GetLength);
		printf("%s\n", datas.MQ_2);*/
		sleep(5); // 加入延时，防止过快循环
	}					
	
	
	//创建连接
	
	close(fd);
	close(cfd);
	
	close(fd1);
	close(cfd1);

	pthread_join(recvdata, NULL);
	pthread_join(recvimage, NULL);

}

